package main

import (
	"context"
	"gin-elas-student-info/config"
	"gin-elas-student-info/routes"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
)

const (
	elasticIndexName = "students"
	elasticTypeName  = "student"
)

var (
	elasticClient *elastic.Client
)

func main() {

	config.InitElasticsearch()
	r := routes.SetupRoutes()

	// 启动服务
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	if err := r.Run(":" + port); err != nil {
		log.Fatal(err)
	}
}
func init1() {

	var err error
	// 创建 Elasticsearch 客户端
	elasticClient, err = elastic.NewClient(
		elastic.SetURL("http://localhost:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	exists, er := elasticClient.IndexExists(elasticIndexName).Do(ctx)

	if er != nil {
		panic(er)
	}

	if !exists {
		// 创建索引
		_, err := elasticClient.CreateIndex(elasticIndexName).Do(ctx)
		if err != nil {
			panic(err)
		}
	}

}

// Elasticsearch 映射
var mapping = `{
	"settings": {
		"number_of_shards": 1,
		"number_of_replicas": 0
	},
	"mappings": {
		"properties": {
			"id": { "type": "keyword" },
			"name": { "type": "text" },
			"age": { "type": "integer" },
			"grade": { "type": "keyword" },
			"major": { "type": "text" },
			"created_at": { "type": "date" }
		}
	}
}`
